/**
 * Copyright 2007-2008 Alex Tkachman
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ait.actors;

import java.util.concurrent.Callable;

public class WorkerThread extends Thread {
    private StealableDeque<Callable> ownQueue = createDeque();
    private StealableDeque<Callable> targetQueue = ownQueue;

    private final Scheduler scheduler;
    private ControlException controlException;

    WorkerThread(Scheduler scheduler, int index) {
        super ("WorkerThread-" + index);
        this.scheduler = scheduler;
        setDaemon(true);
        start ();
    }

    public void run() {
        try {
            scheduler.start.await();
            while (true) {
                workerStep();
            }
        } catch (InterruptedException e) {
        }
    }

    void workerStep() {
        Callable task;

        task = ownQueue.removeLast();

        if (task == null) {
            final WorkerThread randomThread = scheduler.getRandomThread();
            final StealableDeque<Callable> randomQueue = randomThread.ownQueue;
            task = randomQueue.removeFirst();
            if (task == null)
                return;

            final StealableDeque<Callable> savedQueue = targetQueue;
            targetQueue = randomQueue;
            try {
//                Scheduler.debug("executing " + task + ", which belongs to " + randomThread);
                task.call ();
            }
            catch (ControlException ce) {
                // ignore
            }
            catch (Throwable t) { // ignore
                Scheduler.debug(t);
            }
            finally {
                targetQueue = savedQueue;
            }
            return;
        }

        try {
            if (task != null) {
//              Scheduler.debug("executing " + task);
              task.call ();
            }
        }
        catch (ControlException ce) {
            // ignore
        }
        catch (Throwable t) { // ignore but log
            Scheduler.debug(t);
        }
    }

    public void schedule(Callable task) {
//        Scheduler.debug("scheduling " + task);
        if (targetQueue == ownQueue)
           ownQueue.addLast(task);
        else
           targetQueue.addFirst(task);
    }

    public void schedule(Callable[] runnable) {
        for (int i = runnable.length-1; i >= 0; --i) {
//            Scheduler.debug("scheduling " + runnable [i]);
        }
        if (targetQueue == ownQueue) {
           for (int i = runnable.length-1; i >= 0; --i)
             ownQueue.addLast(runnable[i]);
        }
        else {
           for (int i = 0; i != runnable.length; ++i)
             targetQueue.addFirst(runnable [i]);
        }
    }

    public String toString() {
        return getName();
    }

    void throwControl() throws ControlException {
        controlException = new ControlException();
        throw controlException;
    }

    protected StealableDeque<Callable> createDeque() {
        return new LockableDeque<Callable>();
    }
}
